package nqueens.algorithm;

import java.util.List;
import java.util.Random;

import nqueens.config.GAProperties;
import nqueens.core.Chromosome;
import nqueens.core.Population;

/**
 * Class that implements the crossover operator
 * 
 * @author Artur Alves
 * @author Danilo Torres
 * @author Rodrigo Bruno
 * 
 * 
 */
public class CrossoverDefault implements ICrossoverAlgorithm {

	private GAProperties params;

	public CrossoverDefault() {
		params = GAProperties.getInstance();
	}

	@Override
	/**
	 * This method do the crossover operation on a population
	 */
	public void crossover(Population population) {
		Random r = new Random();
		double crossRate = 1.0;
		List<Chromosome> individuals = population.getIndividuals();
		for (int i = 0; i < individuals.size() / 2; i++) {
			Chromosome individual1 = individuals.get(2 * i);
			Chromosome individual2 = individuals.get(2 * i + 1);
			double prob = r.nextDouble();
			if (prob < crossRate) 
				cross(individual1, individual2);
		}
	}

	/**
	 * Do the change on the arrays that represents a individual.
	 * 
	 * @param individual1
	 * @param individual2
	 */
	private void cross(Chromosome individual1, Chromosome individual2) {
		for (int i = params.getInteger(GAProperties.CROSSOVER_PARAM); i < individual1
				.getValues().length; i++) {
			int aux = individual1.getValues()[i];
			individual1.getValues()[i] = individual2.getValues()[i];
			individual2.getValues()[i] = aux;

		}
	}
}
